﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleFileManager.Manager;
using System.IO;

namespace SimpleFileManager.Manager
{
    public class FolderIterator : IFolderIterator
    {
        private string _directoryPath;
        private List<IFilePanelItem> _items=new List<IFilePanelItem>();
        private int _index = 0;
        private Comparison<IFilePanelItem> _comparer;

        private int _totalFiles = 0;
        private int _totalFolders = 0;
        private long _totalSize = 0;

        public int TotalFiles
        {
            get
            {
                return _totalFiles;
            }
        }

        public int TotalFolders
        {
            get
            {
                return _totalFolders;
            }
        }

        public long TotalSize
        {
            get
            {
                return _totalSize;
            }
        }

        public Comparison<IFilePanelItem> Comparer
        {
            get { return _comparer; }
            set { _comparer = value; _items.Sort((i1, i2) => _comparer(i1, i2)); }
        }

        public string DirectoryPath
        {
            get
            {
                return _directoryPath;
            }
        }

        public void Add(IFilePanelItem item)
        {
            _items.Add(item);
            switch (item.Type)
            {
                case FilePanelItemType.File:
                    {
                        _totalFiles++;
                        _totalSize += (new FileInfo(Path.Combine(_directoryPath, item.Name))).Length;
                    }
                    break;
                case FilePanelItemType.Folder: _totalFolders++;
                    break;
            }
        }

        public FolderIterator(string directoryPath)
        {
            _directoryPath = directoryPath;
        }

        public FolderIterator(string directoryPath, Comparison<IFilePanelItem> comparer)
            : this(directoryPath)
        {
            Comparer = comparer;
            _items.Sort((i1, i2) => Comparer(i1,i2));
        }

        public void Sort()
        {
            _items.Sort((i1, i2) => Comparer(i1, i2));
        }

        public void Reverse()
        {
            _items.Reverse();
        }

        public void First()
        {
            _index = 0;
        }

        public void Next()
        {
            _index++;
        }

        public bool IsDone()
        {
            if (_index == _items.Count)
            {
                First();
                return true;
            }
            else
            {
                return false;
            }
        }

        public IFilePanelItem CurrentItem
        {
            get
            {
                return _items[_index];
            }
        }
    }
}
